import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:json_serializer/json_serializer.dart';
import 'package:test_ztna_flutter/ipc/abstract_client.dart';
import 'package:test_ztna_flutter/ipc/data_structures.dart';
import 'package:test_ztna_flutter/ipc/service_manager.dart';

class DataClient extends AbstractClient {

  @override
  String get cmdPipeName => r'\\.\pipe\ztna-edge-tunnel.sock';
  
  @override
  String get eventPipeName => r'\\.\pipe\ztna-edge-tunnel-event.sock';

  DataClient() {
    JsonSerializer.options = JsonSerializerOptions(types: [
      UserType<ServiceFunction>(ServiceFunction.new),
      UserType<SvcResponse>(SvcResponse.new),
      UserType<StatusEvent>(StatusEvent.new),
      UserType<ZitiTunnelStatus>(ZitiTunnelStatus.new)
    ]);
  }

  Function(int a)? onClientConnected;

  @override
  void clientConnected() {
    super.clientConnected();
    onClientConnected?.call(1);
  }

  @override
  void processLine(String line) {
    // TODO line按\n进行分割后再deserialize
    try {
      final evt = deserialize<StatusEvent>(line);
      stdout.writeln('${evt.Op}: line');
      switch (evt.Op) {
        case 'metrics':
          break;
        case 'status':
          break;
        case 'identity':
          
          break;
        case 'service':
          
          break;
        case 'bulkservice':
          
          break;
        case 'shutdown':
          
          break;
        case 'controller':
          
          break;
        default:
          break;
      }
    } catch (e) {
      // TODO
      print('deserialize fail');
    }
  }

  Future<ZitiTunnelStatus?> getStatusAsync() async {
    try {
      await sendAsync(ServiceFunction(command: 'Status'));
      return await readAsync<ZitiTunnelStatus>();
    } on Exception catch(e) {
      // TODO log
    }

    return null;
  }


  Future<void> startZtnaService() async {
    await compute(ServiceManager.start, "ztna");
  }

  Future<void> stopZtnaService() async {
    await compute(ServiceManager.stop, "ztna");
  }
}